<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/12
 * Time: 15:26
 */

namespace App\Admin\Extensions\Form;

use Encore\Admin\Facades\Admin;
use Encore\Admin\Form\Field\Image;
use App\Model\Upload;
use Illuminate\Support\Str;
use Intervention\Image\Constraint;
use Intervention\Image\Facades\Image as InterventionImage;

class UploadImg extends Image
{
    public $useUniqueName = true;

    public function prepare($image)
    {
        if (request()->has(static::FILE_DELETE_FLAG)) {
            return $this->destroy();
        }

        $this->name = $this->getStoreName($image);


        $this->callInterventionMethods($image->getRealPath());

        $path = $this->uploadAndDeleteOriginal($image);



        $ext = pathinfo($this->name, PATHINFO_EXTENSION);

        // We remove extension from file name so we can append thumbnail type
        $thumbPath = Str::replaceLast('.'.$ext, '', $this->name);

        // We merge original name + thumbnail name + extension
        $thumbPath = $thumbPath.'-thumb.'.$ext;
        $imageIntervention = InterventionImage::make($image);

        // Resize image with aspect ratio
        $imageIntervention->resize(100, 100, function (Constraint $constraint) {
            $constraint->aspectRatio();
        })->resizeCanvas(100, 100, 'center', false, '#ffffff');
        if (!is_null($this->storagePermission)) {
            $this->storage->put("{$this->getDirectory()}/{$thumbPath}", $imageIntervention->encode(), $this->storagePermission);
        } else {
            $this->storage->put("{$this->getDirectory()}/{$thumbPath}", $imageIntervention->encode());
        }

        $data = [
            'disk'=>config('admin.upload.disk'),
            'filename'=>$image->getClientOriginalName(),
            'path'=>dirname($path),
            'fullname'=>$path,
            'thumb'=>"{$this->getDirectory()}/{$thumbPath}",
            'mimetype'=>$image->getMimeType(),
            'filesize'=>$image->getSize(),
            'user_id'=>Admin::user()->id,
        ];
        $upload = new Upload;
        $upload->fill($data);
        $upload->save();
        return $upload->id;

    }

    public function render()
    {
        $value = $this->value();
        $newValue = Upload::where('id',$value)->value('fullname');
        if($newValue){
            $this->value($newValue);
        }
        return parent::render();
    }

    public function destroy(){
        parent::destroy();
        if($this->original){
            Upload::query()->find($this->original)->delete();
        }
    }
}
